#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/5/24 14:33
# @Author    :陈文伟
"""
该模块主要负责命令行任务(比如拉取代码，提交代码等)
"""
from invoke import task


def _status(c):
    """
    获取当前分支状态
    :param c:
    :return:
    """
    return c.run('git status').stdout.strip()


def _is_clean(c):
    """
    分支是否干净(是否有未提交文件)
    :param c:
    :return:
    """
    return 'nothing to commit, working tree clean' in _status(c)


def _branch(c):
    """
    获取分支名称
    :param c:
    :return:
    """
    return c.run('git rev-parse --abbrev-ref HEAD').stdout.strip()


@task
def commit(c, msg):
    """
    提交本地分支
    :param c:
    :param msg:
    :return:
    """
    result = _status(c)
    if any(('Changes to be committed' in result,
            'All conflicts fixed but you are still merging.' in result,
            'Changes not staged for commit' in result)):
        c.run('git add -A')
        c.run('git commit -m"{}"'.format(msg))


@task
def pull(c, msg='gx', branch='master'):
    """
    拉取远程分支到本地并安装依赖
    :param c:
    :param msg:
    :param branch:
    :return:
    """
    assert branch == _branch(c)
    commit(c, msg)
    result = c.run('git pull').stdout.strip()
    if any(('error:' in result, 'CONFLICT' in result)):
        raise Exception("错误：代码冲突，请先解决冲突再执行当前命令！")
    c.run('pip install -r requirements.txt')


@task
def push(c, msg='gx', branch='master'):
    """
    推送本地分支到远程并同步依赖文件
    :param c:
    :param msg:
    :param branch:
    :return:
    """
    pull(c, msg, branch)
    c.run('pip freeze > requirements.txt')
    commit(c, '依赖变更')
    c.run('git push')
